<template>
  <div>
    <el-form ref="goodForm" :model="goodForm" :rules="rules" label-width="80px">

      <el-row>
        <el-col :span="6" :offset="1">
          <el-goodForm-item label="商品类型">
            <el-select v-model="goodForm.GTID" placeholder="请选择类型">
              <el-option v-for="item in types" :key="item.GTID" :label="item.Name" :value="item.GTID"></el-option>

            </el-select>
          </el-goodForm-item>
          <el-form-item label="商品图片" prop="Images">
            <el-upload class="avatar-uploader" :action="baseapi + 'Files'" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="goodForm.Images" :src="baseimg+goodForm.Images" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品名称" prop="Name">
            <el-input v-model="goodForm.Name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="Price">
            <el-input-number v-model="goodForm.Price" :precision="2" :step="1" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="商品单位" prop="Unit">
            <el-input v-model="goodForm.Unit"></el-input>
          </el-form-item>
          <el-form-item label="商品描述" prop="Content">
            <el-input type="textarea" v-model="goodForm.Content"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="14" :offset="2">
          <el-form-item label="属性">
            <el-switch v-model="goodForm.Use_Property" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </el-form-item>

          <!-- 循环规格和规格的值 -->
          <el-form-item v-for="(item, index) in specs" :key="item.GSKID" :label="item.Name" v-show="goodForm.Use_Property">
            <el-switch v-model="goodForm.GoodPropertyKey[index].checked" @change="propchange" active-color="#13ce66"
              inactive-color="#ff4949"></el-switch>
            <el-checkbox-group v-show="goodForm.GoodPropertyKey[index].checked"
              v-model="goodForm.GoodPropertyKey[index].GoodPropertyValue">
              <el-checkbox v-for="v in item.Values" :name="item.Name" :key=v.GSVID :label="v.GSVID" :value="v.GSVID">
                {{ v.Value }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>


        </el-col>
      </el-row>



    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button type="primary" @click="submitForm('goodForm')">立即保存</el-button>
      <el-button @click="$emit('change', false)">取 消</el-button>
    </div>


  </div>
</template>

<script>
import basepath from '../../plugins/base.js'
import {mapMutations} from 'vuex'
export default {
  name: 'goodedit',
  data() {
    return {
      baseimg: '',
      baseapi: '',
      imageUrl:'',

      types: [],
      specs: [],

      goodForm: {
        TID: 2,
        Images: '',
        Name: '冻顶乌龙',
        Content: '冻顶乌龙很好喝',
        Price: 18.00,
        Unit: '杯',
        Use_Property: true,
        Sort: 0,
        On_sale:false,
        GoodPropertyKey: [
          {
            gskid: 1,  //规格 主键表  GoodSpecKey  id
            GoodPropertyValue: [],
            checked: true
          },
          {
            gskid: 2,
            GoodPropertyValue: [],
            checked: true
          },
          {
            gskid: 3,
            GoodPropertyValue: [],
            checked: true
          }
        ]
      }

      ,//表单验证规则
      rules: {
        Name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" },
        ],
        Price: [
          { required: true, message: "请输入价格", trigger: "blur" }
        ],
        Unit: [
          { required: true, message: "请输入单位", trigger: "blur" }
        ],
        Content: [
          { required: true, message: "请输入商品描述", trigger: "blur" }
        ],
        Images: [
          { required: true, message: "请选择图片", trigger: "blur" }
        ]
      },
    }
  },
  model: {
    prop: "dialogFormVisible",
    event: "change",
  },
  props: {
    dialogFormVisible: Boolean,
    editData: Object,
  },
  watch: {
    editData: function (newvalue, oldvalue) {
  /*     console.log('newvalue: ', newvalue); */
      this.goodForm = JSON.parse(JSON.stringify(newvalue));
    },
  },
  methods: {
      ...mapMutations(['addCart']),
    //上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == 1) {
        this.$message.success('图片上传成功!');
        this.goodForm.Image = res.data;
        console.log(res.data)
        this.imageUrl = URL.createObjectURL(file.raw);
      } else {
        this.$message.error(res.msg);
      }
    },
    //上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';

      const isLtMB = file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!');
      }
      if (!isLtMB) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return (isJPG || isPNG) && isLtMB;
    },

    //属性切换联动
    propchange() {
      let bol = false;
      this.goodForm.GoodPropertyKey.forEach(v => {
        if (v.checked) {
          bol = true;
        }
      })
      this.goodForm.Use_Property = bol;
    },

    //提交按钮
    submitForm(formName) {
      //进行表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.goodForm));
          console.log(data);
          this
          //对数据进行处理  处理属性规格是否勾选保存
          if (!data.Use_Property) {
            data.GoodPropertyKey = [];
          } else {
            data.GoodPropertyKey.forEach((v, i) => {
              if (!v.checked) {
                data.GoodPropertyKey = data.GoodPropertyKey.filter(v => v.checked);
              }
            });
          }
          if (data.GoodPropertyKey.length < 1) {
            data.Use_Property = false;
            this.goodForm.Use_Property = false;
          }
       
          // //调用Api 保存数据
        this.axios({
            method: "put",
            url: "Goods",
            data: data
          })
            .then((res) => {
              if (res.code > 0) {
                //axios  完成添加
                this.$message({
                  message: res.msg,
                  type: "success",
                  showClose: true,
                  duration: 3000,
                });
                //刷新主页面数据
                this.$emit("refresh");
                //关闭弹窗
                this.$emit("change", false);
              } else {
                this.$message({
                  message: res.msg,
                  type: "error",
                  showClose: true,
                  duration: 3000,
                });
              }
            })
            

        }
        else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  created() {
    this.baseimg = basepath.imgUrl;
    this.baseapi = basepath.apiUrl;

    this.axios({
      method: 'get',
      url: 'Spec'
    }).then(response => {
      this.specs = response.data;
    });

    this.axios({
      method: 'get',
      url: 'GoodsType'
    }).then(response => {
      this.types = response.data;
    })

    this.goodForm = JSON.parse(JSON.stringify(this.editData));
/*     console.log('this.editData: ', this.editData); */

  },
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>